import {
  getAsyncRoutes,
  GetUserInfoApi,
  wwxLoginCode,
  bLoginCode,
} from "@/api/public";
import { IuserInfo } from "@/api/public/types";
import { config } from "@/config";
import router, { asyncRoute } from "@/router";
import { ImenuList } from "@/types";
import { envjudge } from "@/utils";
import { wxDoConfig } from "@/utils/wx-util";
import { defineStore } from "pinia";
import { showConfirmDialog } from "vant";

/** 按钮权限处理 */
function btnFn(menus: ImenuList[], allList: string[]) {
  menus.forEach((item) => {
    if (item.children.length > 0) {
      btnFn(item.children, allList);
    } else {
      allList.push(...item.meta.auths);
    }
  });
}

/** 获取路由参数 */
function getQueryParam(name: string) {
  var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(
    window.location.href
  );
  if (results == null) {
    return null;
  }
  return decodeURIComponent(results[1]) || "";
}

interface IuseUserStore {
  userInfo: IuserInfo;
  authCode: string;
  /** 用户扫码信息(下划线分割，第一个用户id 第二个区域id) */
  // stateInfo: any
  /** 按钮权限 */
  btnList: string[];
  /** 菜单列表 */
  menuList: ImenuList[];
  /** 是否初始化完成 */
  appLoading: boolean;
}

export const useUserStore = defineStore("userStore", {
  // 开启数据持久化
  persist: true,
  state: (): IuseUserStore => {
    return {
      userInfo: {
        id: "",
        token: "",
        expires: "",
        /** 账户名 */
        account: "",
        name: "",
      },
      /** 授权code */
      authCode: "",
      // stateInfo: '',
      btnList: [],
      menuList: [],
      appLoading: true,
    };
  },
  getters: {
    /** 判断有没有登录完成 */
    isWxLoagin: (state) => state.userInfo.token,
    /** 判断是手机企业微信环境 */
    isComWxEnv: () =>
      import.meta.env.MODE !== "production"
        ? true
        : envjudge() === "com-wx-mobile",
    // userInfoRights: (state) => state.userInfo.EmpInfo.Rights,
    // double: (state) => state.count * 2,
  },
  actions: {
    /** 过期重新登录 */
    logInAgain() {
      this.userInfo.token = "";

      window.location.href =
        process.env.NODE_ENV === "development"
          ? window.location.href
          : config.getFlagUrl();
      // process.env.NODE_ENV === 'development' && location.reload()
    },
    /** 授权，拿到token信息 */
    async getUserAuth() {
      this.appLoading = true;
      // 不是企业微信不处理
      if (!this.isComWxEnv) {
        return;
      }

      wxDoConfig(); // wecom-jssdk鉴权
      this.authCode =
        process.env.NODE_ENV === "development"
          ? config.fixedCode
          : (getQueryParam("code") as any);

      if (!this.authCode) {
        this.logInAgain();
      } else {
        // await wwxLoginCode({ code: this.authCode }).then((res) => {
        //   this.userInfo = res.data
        // })
        // 浏览器环境调试
        await bLoginCode({ account: "KaPiBaLa", password: "1233456" }).then(
          (res) => {
            console.log(res);
            this.userInfo = res.data;
          }
        );
      }

      await this.initRouteInfo();
      this.appLoading = false;
    },
    /** 更新用户信息 */
    async updateUserInfo() {
      await GetUserInfoApi().then((res) => {
        this.userInfo = res.data;
      });
    },
    /** 路由权限，路由初始化 */
    async initRouteInfo() {
      await getAsyncRoutes().then((res) => {
        this.menuList = res.data.permissions; // 菜单权限
        btnFn(this.menuList, this.btnList); // 按钮
        // 处理动态路由
        asyncRoute.forEach((item) => {
          if (this.menuList.some((menuItm) => menuItm.path === item.path)) {
            router.addRoute(item);
          }
        });
        // 404处理
        router.addRoute({
          path: "/:pathMatch(.*)", // 使用:pathMatch(.*)作为通配符
          redirect: "/404", // 重定向到404页面
        });
      });
    },
  },
});
